package com.yummy.oneself.keysecret.service;

import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yummy.convention.exception.AssertUtil;

@Service
public class SecretService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private final char[] secretLetterCharacters = {'z','a','c','h','a','r','i','a','h'};
	private final char[] secretSpecialCharacters = {'!','@','#','$','%','^','&','*','(',')'};

	public String getSecret(String appname) {
		AssertUtil.isTrue(StringUtils.isNotBlank(appname));
		int length = appname.length();
		String letters = genLetters(length,secretLetterCharacters);
		String specialCharacter = getSpecialChar(length,secretSpecialCharacters);
		String digitCharacter = getDigitChar(length);
		String secret = letters+specialCharacter+digitCharacter;
		logger.info(appname+":"+secret);
		return secret;
	}

	private String getDigitChar(int length) {
		int digit = length * 3 / 2;
		return String.format("%0"+2+"d", digit);
	}

	private String getSpecialChar(int length, char[] secretSpecialCharacters) {
		int specialCharIndex = length * 3 % secretSpecialCharacters.length;
		return String.valueOf(secretSpecialCharacters[specialCharIndex-1]);
	}

	private String genLetters(int length, char[] secretLetterCharacters) {
		int supperLetterIndex = length * 2 % secretLetterCharacters.length;
		char[] letters = Arrays.copyOf(secretLetterCharacters, secretLetterCharacters.length);
		letters[supperLetterIndex-1] = Character.toUpperCase(letters[supperLetterIndex-1]);
		return new String(letters);
	}

	public String getSecretByAppAndUser(String appname, String username) {
		AssertUtil.isTrue(StringUtils.isNotBlank(appname));
		int length = appname.length();
		String letters = genLetters(length,username.toCharArray());
		String specialCharacter = getSpecialChar(length,secretSpecialCharacters);
		String digitCharacter = getDigitChar(length);
		String secret = letters+specialCharacter+digitCharacter;
		logger.info(appname+":"+secret);
		return secret;
	}
	public static void main(String[] args) {
		SecretService s = new SecretService();
		//System.out.println(s.getSecretByAppAndUser("google","zachariah"));
		System.out.println(s.getSecret("欧易"));
	}
}
